<?php
class KeywordsController extends AppController {
        var $components = array('RequestHandler');
	var $name = 'Keywords';
        var $uses = array("Keyword","KeywordHitLog");
	var $helpers = array('Html', 'Form');

    function beforeFilter() {
                $this->set('page_title','Keywords Management');
                parent::beforeFilter();
                        $this->Auth->allow('destination');
        }


      function destination(){
          $keyword = $_POST['keyword'];
          $domainname = $_POST['domainname'];
           //$keyword = "test";
          //$domainname = "www.google.com";
            if(empty($keyword) || empty($domainname)){
                $this->Session->setFlash(__('There was some problem during query', true));
            }else{
                    $this->Keyword->unbindModel(array("hasMany"=>array("KeywordHitLog")),false);
                    $keywordData =     $this->Keyword->find('first',array("conditions"=>array("Keyword.keyword"=>$keyword,"Website.domain"=>$domainname)));
                     if(!empty($keywordData)){
                            //Update if in the same hour from same ip
                            $existing = $this->KeywordHitLog->find('first',array("conditions"=>array("KeywordHitLog.keyword_id"=>$keywordData['Keyword']['id'],"KeywordHitLog.hit_hour"=>date("H"),"DATE(KeywordHitLog.hit_date)"=>date("Y-m-d"))));
                            if(!empty($existing)){
                                $this->KeywordHitLog->id = $existing['KeywordHitLog']['id'];
                                $this->KeywordHitLog->saveField('hit_count',$existing['KeywordHitLog']['hit_count']+1);
                            }else{
                                // Log an entry for hit
                                        $this->data['KeywordHitLog']['keyword_id'] = $keywordData['Keyword']['id'];
                                        $this->data['KeywordHitLog']['ip_address'] = $_SERVER['REMOTE_ADDR'];
                                        $this->data['KeywordHitLog']['hit_count'] = 1;
                                        $this->data['KeywordHitLog']['hit_hour'] = date("H");
                                        $this->data['KeywordHitLog']['hit_date'] = date("Y-m-d H:i:s");
                                        $this->KeywordHitLog->create();
                                       $this->KeywordHitLog->save($this->data);
                            }
                                       
                    }
                    $this->set('keywordData',$keywordData);
            }

      }



	function index() {           
		$this->Keyword->recursive = 0;
                 $this->paginate['Keyword']['order'] = 'Keyword.id DESC';                    
                 $this->paginate['Keyword']['conditions'] = array();
                   $this->paginate['Keyword']['conditions']['Website.user_id'] = $this->Auth->User('id');
            App::import('Core', 'Sanitize');
        if (isset($this->params['named']['q'])) {          
            $q=Sanitize::clean($this->params['named']['q']);
              $this->set('q',$q);
            $this->paginate['Keyword']['conditions']['OR'] = array(
                'Keyword.keyword LIKE' => '%' . $q . '%',
                'Keyword.campaign_reference LIKE' => '%' . $q . '%'
            );
        }
         if (isset($this->params['named']['website'])) {
                $website =Sanitize::clean($this->params['named']['website']);
             $this->paginate['Keyword']['conditions']['Keyword.website_id']  = $website;
         }

        
                  $this->set('keywords', $this->paginate());

                  $websites = $this->Keyword->Website->find('list',array("fields"=>array("Website.id","Website.website_name"),"conditions"=>array("Website.user_id"=>$this->Auth->User('id'))));
                  $this->set(compact('websites'));
	}

        
        
	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Keyword.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('keyword', $this->Keyword->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Keyword->create();
			if ($this->Keyword->save($this->data)) {
				$this->Session->setFlash(__('The Keyword has been saved', true),'success');
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Keyword could not be saved. Please, try again.', true),'error');
			}
		}
		$websites = $this->Keyword->Website->find('list',array("fields"=>array("Website.id","Website.website_name"),"conditions"=>array("Website.user_id"=>$this->Auth->User('id'))));
		$this->set(compact('websites'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Keyword', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Keyword->save($this->data)) {
				$this->Session->setFlash(__('The Keyword has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Keyword could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Keyword->read(null, $id);
                        if($this->data['Website']['user_id']!=$this->Auth->User('id')){
                                $this->Session->setFlash(__('You are not the owner of the keyword. Please, try again.', true),'notice');
                                $this->redirect(array("action"=>"index"));
                        }
		}
		$websites = $this->Keyword->Website->find('list',array("fields"=>array("Website.id","Website.website_name"),"conditions"=>array("Website.user_id"=>$this->Auth->User('id'))));
		$this->set(compact('websites'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Keyword', true));
			$this->redirect(array('action'=>'index'));
		}
                $data = $this->Keyword->read(null, $id);
                        if($data['Website']['user_id']!=$this->Auth->User('id')){
                                $this->Session->setFlash(__('You are not the owner of the keyword. Please, try again.', true),'notice');
                                $this->redirect(array("action"=>"index"));
                        }
                        
		if ($this->Keyword->delete($id)) {
			$this->Session->setFlash(__('Keyword deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}

        function export(){            
                $data = $this->Keyword->find("all",array("conditions"=>array("Website.user_id"=>$this->Auth->User('id'))));
                  $fileName = "downloads/".date("Y-m-d")."_keywords_". ".csv";
                    if(!(file_exists($fileName))){
                        $fp = fopen($fileName, "a");
                    }else{
                        $fp = fopen($fileName, "w");
                    }

                    $headers = array('S. NO.','Website','Keywords','CampaignReference','DestinationUrl');
                   fputcsv($fp, $headers);
                   $count=1;
                      foreach($data as $logs){
                                $dataarray=array();
                                $dataarray[]="'".$count."'";
                                $dataarray[]="'".$logs['Website']['website_name']."'";
                                $dataarray[]="'".$logs['Keyword']['keyword']."'";
                                $dataarray[]="'".$logs['Keyword']['campaign_reference']."'";                                
                                $dataarray[]="'".$logs['Keyword']['destination_url']."'";
                      fputcsv($fp, $dataarray);
                    $count++;
            }
            fclose($fp);
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Content-Type: application/octet-stream");
                header("Content-Length: " . filesize($fileName));
                header("Content-Disposition: attachment; filename=".$fileName);
                $this->readfile_chunked($fileName);
                
        }
        
        
    function admin_index($website_id=null) {           
        if(empty($website_id)){
             $this->Session->setFlash(__('Invalid Website.', true),'error');
             $this->redirect(array('controller'=>'users','action'=>'index'));           
        }
        $this->set('website_id',$website_id);
		$this->Keyword->recursive = 0;
                 $this->paginate['Keyword']['order'] = 'Keyword.id DESC';                    
                 $this->paginate['Keyword']['conditions'] = array();
                  
            App::import('Core', 'Sanitize');
        if (isset($this->params['named']['q'])) {          
            $q=Sanitize::clean($this->params['named']['q']);
              $this->set('q',$q);
            $this->paginate['Keyword']['conditions']['OR'] = array(
                'Keyword.keyword LIKE' => '%' . $q . '%',
                'Keyword.campaign_reference LIKE' => '%' . $q . '%'
            );
        }
        
        $this->paginate['Keyword']['conditions']['Keyword.website_id']  = $website_id;
         $this->set('keywords', $this->paginate());

	}
        function admin_edit($website_id,$id = null) {
                if(empty($website_id)){
                     $this->Session->setFlash(__('Invalid Website.', true),'error');
                     $this->redirect(array('controller'=>'users','action'=>'index'));           
                }
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Keyword', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Keyword->save($this->data)) {
				$this->Session->setFlash(__('The Keyword has been saved', true),'success');
				$this->redirect(array('action'=>'index/'.$website_id));
			} else {
				$this->Session->setFlash(__('The Keyword could not be saved. Please, try again.', true),'error');
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Keyword->read(null, $id);                       
		}
		
	}
        function admin_add($website_id=null) {
                if(empty($website_id)){
                     $this->Session->setFlash(__('Invalid Website.', true),'error');
                     $this->redirect(array('controller'=>'users','action'=>'index'));           
                }
                $this->set('website_id',$website_id);
		
		if (!empty($this->data)) {
                    $this->data['Keyword']['website_id'] = $website_id;
			if ($this->Keyword->save($this->data)) {
				$this->Session->setFlash(__('The Keyword has been saved', true),'success');
				$this->redirect(array('action'=>'index/'.$website_id));
			} else {
				$this->Session->setFlash(__('The Keyword could not be saved. Please, try again.', true),'error');
			}
		}
		
		
	}        
   	function admin_delete($website_id,$id = null) {
                if(empty($website_id)){
                     $this->Session->setFlash(__('Invalid Website.', true),'error');
                     $this->redirect(array('controller'=>'users','action'=>'index'));           
                }            
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Keyword', true),'erro');
			$this->redirect(array('action'=>'index/'.$website_id));
		}        
		if ($this->Keyword->delete($id)) {
			$this->Session->setFlash(__('Keyword deleted', true),'success');
			$this->redirect(array('action'=>'index/'.$website_id));
		}
	}     

}
?>